import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { insertCartAPI, getCartListAPI, deleteCartAPI } from '@/apis/cart'
import { get } from '@vueuse/core'
export const useCartStore = defineStore('cart', () => {
  const cartList = ref([])
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)

  const getCartList = async () => {
    const res = await getCartListAPI()
    cartList.value = res.result
  }
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      console.log('登录了', skuId, count);
      await insertCartAPI({ skuId, count })
      getCartList()
    }
    else {
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if (item) {
        item.count += goods.count
      } else {
        cartList.value.push(goods)
      }
      console.log(cartList);
    }
  }

  const deleteCart =async (skuId) => {
    if (isLogin.value) {
      await deleteCartAPI([skuId])
      getCartList()
    } else {
      let index = cartList.value.find(item => item.skuId === skuId)
      cartList.value.splice(index, 1)
      //方式 二
      // cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }

  //退出登录清空购物车数据
  const clearCart = async () => {
    cartList.value = []
  }

  let allCount = computed(() => {
    return cartList.value.reduce((preValue, item) => {
      return preValue + item.count
    }, 0)
  })

  let allPrice = computed(
    () => cartList.value.reduce(
      (preValue, item) => preValue + item.count * item.price
      , 0))

  //全选判断功能
  const isSelectAll = computed(() => {
    return cartList.value.every(item => item.selected === true)
  })

  //选中商品数量
  const selectedCount = computed(() => {
    return cartList.value.filter(item => item.selected === true).reduce(
      (preValue, item) => preValue + item.count
      , 0)
  })

  //选中商品总价
  const selectedPrice = computed(() =>
    cartList.value.filter(item => item.selected === true).reduce((preValue, item) => preValue + item.count * item.price, 0
    ))
  //全选功能
  const selectAll = (sel) => {
    cartList.value.forEach(item => item.selected = sel)
  }
  const updateSelect = (i, sel) => {
    cartList.value.find(item => item.skuId === i).selected = sel
  }
  return {
    cartList, addCart, deleteCart, allCount, allPrice, updateSelect
    , isSelectAll, selectAll, selectedPrice, selectedCount,clearCart,getCartList
  }
}, {
  persist: true
}
)